package web

import (
	"Redbook/redbook/internal/Domain"
	"Redbook/redbook/internal/server"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type ArticleContol struct {
	Service server.ArticleService
}

type AticleVo struct {
	Writer  string `form:"writer"`
	Title   string `form:"title"`
	Content string `form:"content"`
}
type Man struct {
	ID     string `form:"user_id"`
	Passwd string `form:"passwd"`
}

func NewArticlControl(service server.ArticleService) *ArticleContol {
	return &ArticleContol{
		Service: service,
	}
}

func (a *ArticleContol) RegistRouter(server *gin.Engine) {
	article := server.Group("/article")
	article.POST("/new", a.Save)
	article.Any("/err", a.Error)
	article.Any("/sucess", a.Sucess)
	article.GET("/new", a.New)
	article.Any("/publish", a.Publish)
}
func (a *ArticleContol) New(c *gin.Context) {
	c.HTML(http.StatusOK, "new.gohtml", nil)
}
func (a *ArticleContol) Error(c *gin.Context) {
	c.String(http.StatusForbidden, "err", c.Request.Context())
}
func (a *ArticleContol) Publish(c *gin.Context) {
	var art AticleVo
	c.Bind(&art)
	err := a.Service.Publish(c.Request.Context(), Domain.Articl{
		Title:   art.Title,
		Content: art.Content,
		Writter: art.Writer,
	})
	if err != nil {
		c.Redirect(http.StatusTemporaryRedirect, "/err")
	} else {
		c.Redirect(http.StatusTemporaryRedirect, "/sucess")
	}
}
func (a *ArticleContol) Save(c *gin.Context) {
	var art AticleVo
	c.Bind(&art)
	id := 0
	id, err := a.Service.Save(c.Request.Context(), Domain.Articl{
		ID:      id,
		Title:   art.Title,
		Content: art.Content,
		Writter: art.Writer,
	})
	if err != nil {
		c.Redirect(http.StatusTemporaryRedirect, "/err")
	} else {
		c.String(http.StatusOK, fmt.Sprintf("sucessful"))
		//c.Redirect(http.StatusTemporaryRedirect, "/sucess")
	}
}
func (a *ArticleContol) Sucess(c *gin.Context) {
	c.String(http.StatusOK, "sucessful", nil)
}
